/**
 * 项目名：admin
 * 包名：com.xuebang.admin.controller
 * 文件名：AdController.java
 * 版本信息：@version 1.0
 * 日期：2014-2-17-下午3:46:14
 */
package com.xuebang.admin.controller;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xuebang.admin.entity.Links;
import com.xuebang.admin.entity.OperatorRules;
import com.xuebang.admin.service.LinkService;
import com.xuebang.admin.util.JsonUtil;
import com.xuebang.admin.web.Result;

/**
 * 项目名称：admin
 * 类名称：AdController
 * 类描述：
 * 创建人：xuyang
 * 创建时间：2014-2-17 下午3:46:14
 * 修改人：xuyang
 * 修改时间：2014-2-17 下午3:46:14
 * 修改备注：
 * @version 
 */
@Controller
@RequestMapping("/ad")
public class AdsController extends BaseController{

	@Inject
	LinkService linkService; 
	
	/**
	 * 展示所有的幻灯片
	 */
	@RequestMapping(value="/showAds")
	public String showAds(Model model){
		
		List<Links> links = this.linkService.showAds();
		if(links==null){
			links = new ArrayList<Links>();
		}
		model.addAttribute("links",links);
		return "/ad/showAds";
	}
	
	/**
	 * 展示所有的
	 */
	@RequestMapping(value="/operate")
	public String operate(Model model){
		
		if(!hasPerm(OperatorRules.PERM_AD)){
			return "/account/no_perm";
		}
		
		return "/ad/operate";
	}
	
	/**
	 * 跳转到增加页面
	 */
	@RequestMapping(value="/add")
	public String add(Links adLink,Model model){
		
		model.addAttribute("adLink",adLink);
		return "/ad/add";
	}
	
	/**
	 * 跳转到更新页面
	 */
	@RequestMapping(value="/update")
	public String update(Integer linkId,Model model){

		List<Integer> lstAdsIndex = new ArrayList<Integer>();
		List<Links> links = this.linkService.showAds();
		Links adLink = null;
		int i = 1;
		int intFlag = 0;
		//System.out.println("linkId"+linkId);
		for(Links link: links){
			//System.out.println(link.getId());
			if(link.getId().intValue()==linkId){
				adLink = link;
				intFlag = i;
			}
			lstAdsIndex.add(i++);
		}
		
		adLink.setSort(intFlag);
		model.addAttribute("adLink",adLink);
		model.addAttribute("lstAdsIndex",lstAdsIndex);
		
		return "/ad/update";
	}
	
	/**
	 * 增加幻灯片
	 */
	@RequestMapping(value="/toAdd",method = RequestMethod.POST,produces = "text/plain;charset=UTF-8")
	public String toAdd(@Valid Links adLink,HttpServletRequest request,Model model){
		
		try{
			// 检查
			String strCheckResult = adValidate(adLink);
			if(strCheckResult==""){
				// 确保链接自动添加http
				addHttp(adLink);
				this.linkService.addLinks(adLink);
				model.addAttribute("resultType",1);
				model.addAttribute("resultMessage","增加成功");
			} else {
				model.addAttribute("resultType",0);
				model.addAttribute("resultMessage",strCheckResult);
			}
		}catch(Exception e){
			e.printStackTrace();
			model.addAttribute("resultType",0);
			model.addAttribute("resultMessage","增加失败");
		}
		
		model.addAttribute("adLink",adLink);
		return "/ad/add";
	}
	
	/**
	 * 更新幻灯片
	 */
	@RequestMapping(value="/toUpdate",method = RequestMethod.POST,produces = "text/plain;charset=UTF-8")
	public String toUpdate(@Valid Links adLink,HttpServletRequest request,Model model){

		try{
			// 检查
			String strCheckResult = adValidate(adLink);
			if(strCheckResult==""){
				// 确保链接自动添加http
				addHttp(adLink);
				this.linkService.updateLinksItems(adLink);
				model.addAttribute("resultType",1);
				model.addAttribute("resultMessage","更新成功");
			} else {
				model.addAttribute("resultType",0);
				model.addAttribute("resultMessage",strCheckResult);
			}
		}catch(Exception e){
			e.printStackTrace();
			model.addAttribute("resultType",0);
			model.addAttribute("resultMessage","更新失败");
		}
		if(adLink!=null&&adLink.getId()!=null){
			update(adLink.getId(),model);
		}
		//model.addAttribute("adLink",adLink);
		return "/ad/update";
	}
	
	/**
	 * 增加幻灯片
	 */
	@RequestMapping(value="/toDelete",method = RequestMethod.POST,produces = "text/plain;charset=UTF-8")
	public @ResponseBody String toDelete(String strAdIds){
		
		try{
			this.linkService.deleteLinks(strAdIds);
			return JsonUtil.dump(Result.success("删除成功"));
		}catch(Exception e){
			e.printStackTrace();
			return JsonUtil.dump(Result.error("删除失败"));
		}
	}
	
	/**
	 * 改变位置
	 */
	@RequestMapping(value="changePos",method=RequestMethod.POST,produces = "text/plain;charset=UTF-8")
	public @ResponseBody String changePos(Integer adId,Integer intFlag){
		
		Links adLink = this.linkService.loadLink(adId);
		if(adLink!=null){
			List<Links> lstAdLinks = this.linkService.showAds();
			if(lstAdLinks!=null &&lstAdLinks.size()>0 ){
				if(lstAdLinks.size()>1){
					Integer intCurrentIndex = 0;
					// 找出
					int intIndex = 0;
					for(Links tmpLink:lstAdLinks){
						if(tmpLink.getId().intValue()==adId.intValue()){
							intCurrentIndex = intIndex;
							break;
						}
						intIndex ++;
					}
					Integer intDesIndex = null;
					// 上升
					if(intFlag == 0){
						if(intIndex > 0){
							intDesIndex = intCurrentIndex-1;
						}
					} else {
					// 下降
						if(intIndex < lstAdLinks.size()-1){
							intDesIndex = intCurrentIndex+1;
						}
					}
					if(intDesIndex!=null){
						try{
							Integer intTmp = lstAdLinks.get(intDesIndex).getSort();
							lstAdLinks.get(intDesIndex).setSort(lstAdLinks.get(intCurrentIndex).getSort());
							lstAdLinks.get(intCurrentIndex).setSort(intTmp);
							this.linkService.updateLinks(lstAdLinks.get(intCurrentIndex));
							this.linkService.updateLinks(lstAdLinks.get(intDesIndex));
							return JsonUtil.dump(Result.success("修改成功"));
						} catch(Exception e){
							return JsonUtil.dump(Result.error("修改失败"));
						}
					} else {
						return JsonUtil.dump(Result.error("修改成功"));
					}
				}  else {
					return JsonUtil.dump(Result.error("修改失败"));
				}
			} else {
				//ERROR
				return JsonUtil.dump(Result.error("修改失败"));
			}
		} else {
			//ERROR
			return JsonUtil.dump(Result.error("修改失败"));
		}
	}
	
	/**
	 * 检查 
	 * 
	 */
	private String adValidate(Links adLink){
		
		if(adLink==null){
			return "表单提交异常";
		}

		String strResult = "";
		// name不能为空
		if(adLink.getTheme()==null || "".equals(adLink.getTheme().trim())){
			strResult = "主题不能为空";
		}

		return strResult;
	}
	
	/**
	 * 自动添加http
	 */
	private void addHttp(Links adLink){
		
		if(adLink!=null){
			String strUrl = adLink.getUrl();
			if(strUrl!=null&&!"".equals(strUrl.trim())){
				if(!strUrl.contains("http://")&&!strUrl.contains("https://")){
					strUrl="http://" + strUrl;
					adLink.setUrl(strUrl);
				}
			}
		}
	}
}
